import React, { createContext, useContext, useState, useCallback, useEffect } from 'react';
import { v4 as uuidv4 } from 'uuid';
import {
  type AIChatState,
  type AIChatContextType,
  type ChatMessage,
  type Conversation,
  MessageSender,
  type ConversationSummary,
  TimeGroup,
  type GroupedConversations
} from '@/types/aiChat';
// Removed mockConversations import as data will come from API layer
// import { mockConversations } from '@/data/mockChat'; 
import {
  fetchConversationsAPI,
  createConversationAPI,
  sendMessageAPI,
  deleteConversationAPI
} from '../api/agent'; // Import new API functions

// 创建初始状态
const initialState: AIChatState = {
  conversations: [],
  currentConversationId: null,
  isOpen: false,
  isTyping: false,
  isSidebarOpen: true
};

// 创建上下文
const AIChatContext = createContext<AIChatContextType | undefined>(undefined);

// Removed commonQuestions and getAIResponse as they are now in api/chat.ts

// 提供者组件
export const AIChatProvider: React.FC<{children: React.ReactNode}> = ({ children }) => {
  const [state, setState] = useState<AIChatState>(initialState);
  const [isLoading, setIsLoading] = useState<boolean>(true); // For initial load

  // Load initial conversations
  useEffect(() => {
    const loadInitialData = async () => {
      setIsLoading(true);
      try {
        const fetchedConversations = await fetchConversationsAPI();
        setState(prev => ({
          ...prev,
          conversations: fetchedConversations,
          currentConversationId: fetchedConversations[0]?.id || null,
        }));
      } catch (error) {
        console.error("Failed to fetch initial conversations:", error);
        // Handle error appropriately, maybe set an error state
      } finally {
        setIsLoading(false);
      }
    };
    loadInitialData();
  }, []);

  // 获取当前对话
  const getCurrentConversation = useCallback((): Conversation | null => {
    if (!state.currentConversationId) return null;
    return state.conversations.find(conv => conv.id === state.currentConversationId) || null;
  }, [state.currentConversationId, state.conversations]);
  
  // 获取当前对话的消息
  const getCurrentMessages = useCallback((): ChatMessage[] => {
    const currentConversation = getCurrentConversation();
    return currentConversation?.messages || [];
  }, [getCurrentConversation]);
  
  // 创建新对话
  const createNewConversation = useCallback(async () => {
    try {
      const newConversation = await createConversationAPI();
      setState(prev => ({
        ...prev,
        conversations: [newConversation, ...prev.conversations],
        currentConversationId: newConversation.id,
        isOpen: true // Ensure chat opens when a new conversation is created
      }));
    } catch (error) {
      console.error("Failed to create new conversation:", error);
      // Handle error (e.g., show a notification to the user)
    }
  }, []);
  
  // 选择对话
  const selectConversation = useCallback((conversationId: string) => {
    setState(prev => ({
      ...prev,
      currentConversationId: conversationId
    }));
  }, []);
  
  // 删除对话
  const deleteConversation = useCallback(async (conversationId: string) => {
    try {
      await deleteConversationAPI(conversationId); // Call API first
      setState(prev => {
        const updatedConversations = prev.conversations.filter(conv => conv.id !== conversationId);
        let newCurrentId = prev.currentConversationId;
        if (prev.currentConversationId === conversationId) {
          newCurrentId = updatedConversations.length > 0 ? updatedConversations[0].id : null;
        }
        return {
          ...prev,
          conversations: updatedConversations,
          currentConversationId: newCurrentId
        };
      });
    } catch (error) {
      console.error(`Failed to delete conversation ${conversationId}:`, error);
      // Handle error
    }
  }, []);
  
  // 发送消息
  const sendMessage = useCallback(async (content: string) => {
    if (!content.trim() || !state.currentConversationId) return;
    
    const currentConvId = state.currentConversationId; // Capture for use in async operations
    const now = new Date().toISOString();
    
    const userMessage: ChatMessage = {
      id: uuidv4(),
      content,
      sender: MessageSender.USER,
      timestamp: now
    };
    
    // Optimistically update UI with user message and set typing to true
    setState(prev => {
      const updatedConversations = prev.conversations.map(conv => {
        if (conv.id === currentConvId) {
          const isFirstUserMessage = !conv.messages.some(msg => msg.sender === MessageSender.USER);
          const updatedTitle = isFirstUserMessage && content.length > 0 ? 
            (content.length > 20 ? `${content.substring(0, 20)}...` : content) : 
            conv.title;
          
          return {
            ...conv,
            title: updatedTitle,
            messages: [...conv.messages, userMessage],
            updatedAt: now
          };
        }
        return conv;
      });
      return { ...prev, conversations: updatedConversations, isTyping: true };
    });
    
    try {
      const aiMessage = await sendMessageAPI(currentConvId, content);
      
      setState(prev => {
        const updatedConversations = prev.conversations.map(conv => {
          if (conv.id === currentConvId) {
            return {
              ...conv,
              messages: [...conv.messages, aiMessage],
              updatedAt: new Date(aiMessage.timestamp).toISOString() // Use AI message timestamp
            };
          }
          return conv;
        });
        return { ...prev, conversations: updatedConversations, isTyping: false };
      });
    } catch (error) {
      console.error("Failed to send message or get AI response:", error);
      // Optionally, revert user message or add an error message to chat
      setState(prev => ({ ...prev, isTyping: false }));
    }
  }, [state.currentConversationId, state.conversations]); // Added state.conversations to dependencies

  // 打开/关闭聊天窗口
  const toggleChat = useCallback(() => {
    setState(prev => ({ ...prev, isOpen: !prev.isOpen }));
  }, []);

  // 关闭聊天窗口
  const closeChat = useCallback(() => {
    setState(prev => ({ ...prev, isOpen: false }));
  }, []);

  // 打开/关闭侧边栏
  const toggleSidebar = useCallback(() => {
    setState(prev => ({ ...prev, isSidebarOpen: !prev.isSidebarOpen }));
  }, []);

  // Helper function to generate conversation preview
  const getConversationPreview = useCallback((conversation: Conversation): string => {
    if (!conversation.messages || conversation.messages.length === 0) {
      return "No messages yet.";
    }
    const lastMessage = conversation.messages[conversation.messages.length - 1];
    let preview = lastMessage.sender === MessageSender.USER ? "You: " : "";
    preview += lastMessage.content;
    return preview.length > 50 ? `${preview.substring(0, 47)}...` : preview;
  }, []);

  // Get grouped conversations
  const getGroupedConversations = useCallback((): GroupedConversations => {
    const groups: GroupedConversations = {
      [TimeGroup.TODAY]: [],
      [TimeGroup.WEEK]: [],
      [TimeGroup.MONTH]: [],
      [TimeGroup.OLDER]: [],
    };

    const now = new Date();
    // Start of today (00:00:00)
    const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    
    // Start of 7 days ago (from start of today)
    const sevenDaysAgoStart = new Date(todayStart);
    sevenDaysAgoStart.setDate(todayStart.getDate() - 7);

    // Start of 30 days ago (from start of today)
    const thirtyDaysAgoStart = new Date(todayStart);
    thirtyDaysAgoStart.setDate(todayStart.getDate() - 30);

    // Sort conversations by updatedAt descending before grouping
    const sortedConversations = [...state.conversations].sort(
      (a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()
    );

    sortedConversations.forEach(conv => {
      const summary: ConversationSummary = {
        id: conv.id,
        title: conv.title,
        preview: getConversationPreview(conv),
        createdAt: conv.createdAt,
        updatedAt: conv.updatedAt,
      };

      const updatedAtDate = new Date(conv.updatedAt);

      if (updatedAtDate >= todayStart) {
        groups[TimeGroup.TODAY]?.push(summary);
      } else if (updatedAtDate >= sevenDaysAgoStart) {
        groups[TimeGroup.WEEK]?.push(summary);
      } else if (updatedAtDate >= thirtyDaysAgoStart) {
        groups[TimeGroup.MONTH]?.push(summary);
      } else {
        groups[TimeGroup.OLDER]?.push(summary);
      }
    });
    
    // Remove empty groups for a cleaner output
    for (const groupKey in groups) {
        if (groups[groupKey as TimeGroup]?.length === 0) {
            delete groups[groupKey as TimeGroup];
        }
    }

    return groups;
  }, [state.conversations, getConversationPreview]);

  // 清空所有对话 (示例 - 如果需要此功能)
  // const clearAllConversations = useCallback(async () => {
  //   // Potentially call an API to clear all conversations on the backend
  //   // await clearAllConversationsAPI(); 
  //   setState(prev => ({
  //     ...prev,
  //     conversations: [],
  //     currentConversationId: null,
  //   }));
  // }, []);

  return (
    <AIChatContext.Provider value={{ 
      ...state,
      isLoading, // Provide loading state
      getCurrentConversation,
      getCurrentMessages,
      createNewConversation,
      selectConversation,
      deleteConversation,
      sendMessage,
      toggleChat,
      closeChat,
      toggleSidebar,
      getGroupedConversations
      // clearAllConversations (if added)
    }}>
      {children}
    </AIChatContext.Provider>
  );
};

// 自定义钩子
export const useAIChat = (): AIChatContextType => {
  const context = useContext(AIChatContext);
  if (context === undefined) {
    throw new Error('useAIChat must be used within an AIChatProvider');
  }
  return context;
};
